/**
 * 请求拦截器
 * @param {*} vm 
 */
import {
	generateAesKey,
	encryptBase64,
	encryptWithAes,
	encrypt
} from '@/utils/crypto.js'

module.exports = (vm) => {
	uni.$u.http.interceptors.request.use((config) => {
		config.data = config.data || {}
		// config.header.token = vm.$store.state.userInfo.token
		if(!(config.custom.isToken === false)) {
			config.header.Authorization = 'Bearer ' + vm.$store.state.token
			config.header.clientid = 'e5cd7e4891bf95d1d19206ce24a7b32e'
		}
		// 是否需要加密
		const isEncrypt = config.custom.isEncrypt === true;

		// loading加载
		if (config.custom.loading) {
			uni.showLoading({
				title: config.custom.loading
			})
		}
		
		// 当开启参数加密
		if (isEncrypt && (config.method === 'POST' || config.method === 'put')) {
			// 生成一个 AES 密钥
			const aesKey = generateAesKey();
			config.header = {
				"Content-Type":"application/json;charset=UTF-8",
				"encrypt-key": encrypt(encryptBase64(aesKey))
			};
			config.data = typeof config.data === 'object' ? encryptWithAes(JSON.stringify(config.data),
				aesKey) : encryptWithAes(config.data, aesKey);
		}

		return config
	}, config => {
		return Promise.reject(config)
	})
}